// 敌人类
class Enemy {
    constructor(type = 'regular') {
        this.type = type;
        this.health = 50;
        this.speed = 2;
        this.damage = 10;
        this.attackRange = 2;
        this.attackSpeed = 1; // 攻击间隔（秒）
        this.lastAttackTime = 0;
        this.isAttacking = false;
        this.target = null;
        this.aggroRange = 15;
        
        // 根据敌人类型调整属性
        this.setupEnemyType();
        
        // 创建敌人模型
        this.createEnemyMesh();
    }
    
    setupEnemyType() {
        switch(this.type) {
            case 'regular':
                this.health = 50;
                this.speed = 2;
                this.damage = 10;
                this.aggroRange = 15;
                break;
            case 'fast':
                this.health = 30;
                this.speed = 4;
                this.damage = 8;
                this.aggroRange = 20;
                break;
            case 'tank':
                this.health = 100;
                this.speed = 1.5;
                this.damage = 15;
                this.aggroRange = 10;
                break;
            case 'boss':
                this.health = 200;
                this.speed = 1.8;
                this.damage = 20;
                this.aggroRange = 25;
                // 添加额外的BOSS特性
                this.phase = 1;
                this.maxHealth = this.health;
                break;
        }
    }
    
    createEnemyMesh() {
        // 根据敌人类型创建不同的模型
        let geometry, material;
        
        switch(this.type) {
            case 'regular':
                geometry = new THREE.CapsuleGeometry(0.4, 0.8, 8, 16);
                material = new THREE.MeshPhongMaterial({ color: 0xff0000 });
                break;
            case 'fast':
                geometry = new THREE.CapsuleGeometry(0.3, 0.6, 8, 16);
                material = new THREE.MeshPhongMaterial({ color: 0xff6600 });
                break;
            case 'tank':
                geometry = new THREE.CapsuleGeometry(0.6, 1.2, 8, 16);
                material = new THREE.MeshPhongMaterial({ color: 0xff3333 });
                break;
            case 'boss':
                geometry = new THREE.CapsuleGeometry(0.8, 1.6, 8, 16);
                material = new THREE.MeshPhongMaterial({ color: 0x990000 });
                // 添加BOSS光环
                const auraGeometry = new THREE.SphereGeometry(1.2, 32, 32);
                const auraMaterial = new THREE.MeshBasicMaterial({
                    color: 0xff0000,
                    transparent: true,
                    opacity: 0.2,
                    wireframe: true
                });
                this.auraMesh = new THREE.Mesh(auraGeometry, auraMaterial);
                break;
        }
        
        this.mesh = new THREE.Mesh(geometry, material);
        this.mesh.position.y = 0.5;
        this.mesh.castShadow = true;
        
        // 如果是BOSS，添加光环到场景
        if (this.auraMesh) {
            this.auraMesh.position.copy(this.mesh.position);
        }
    }
    
    update(deltaTime, playerPosition) {
        this.target = playerPosition;
        
        // 检查是否在攻击范围内
        const distance = this.distanceToPlayer();
        
        if (distance < this.attackRange) {
            this.attack(deltaTime);
        } else if (distance < this.aggroRange) {
            this.chasePlayer(deltaTime);
        } else {
            this.patrol(deltaTime);
        }
        
        // 更新BOSS光环位置
        if (this.auraMesh) {
            this.auraMesh.position.copy(this.mesh.position);
        }
        
        // 处理BOSS阶段变化
        if (this.type === 'boss' && this.health < this.maxHealth * 0.5 && this.phase === 1) {
            this.enterPhase2();
        }
    }
    
    distanceToPlayer() {
        if (!this.target) return Infinity;
        
        const dx = this.mesh.position.x - this.target.x;
        const dz = this.mesh.position.z - this.target.z;
        return Math.sqrt(dx * dx + dz * dz);
    }
    
    chasePlayer(deltaTime) {
        if (!this.target) return;
        
        // 计算方向向量
        const direction = new THREE.Vector3(
            this.target.x - this.mesh.position.x,
            0,
            this.target.z - this.mesh.position.z
        ).normalize();
        
        // 应用移动
        this.mesh.position.x += direction.x * this.speed * deltaTime;
        this.mesh.position.z += direction.z * this.speed * deltaTime;
        
        // 使敌人面向玩家
        this.mesh.lookAt(this.target.x, this.mesh.position.y, this.target.z);
        
        this.isAttacking = false;
    }
    
    patrol(deltaTime) {
        // 简单的巡逻行为 - 随机移动
        if (!this.patrolDirection || Math.random() < 0.01) {
            this.patrolDirection = new THREE.Vector3(
                Math.random() - 0.5,
                0,
                Math.random() - 0.5
            ).normalize();
        }
        
        // 应用巡逻移动
        this.mesh.position.x += this.patrolDirection.x * this.speed * 0.5 * deltaTime;
        this.mesh.position.z += this.patrolDirection.z * this.speed * 0.5 * deltaTime;
        
        // 限制敌人在地图范围内
        const mapSize = 45;
        if (this.mesh.position.x > mapSize) this.mesh.position.x = mapSize;
        if (this.mesh.position.x < -mapSize) this.mesh.position.x = -mapSize;
        if (this.mesh.position.z > mapSize) this.mesh.position.z = mapSize;
        if (this.mesh.position.z < -mapSize) this.mesh.position.z = -mapSize;
        
        this.isAttacking = false;
    }
    
    attack(deltaTime) {
        const currentTime = Date.now() / 1000;
        
        // 检查是否可以攻击
        if (currentTime - this.lastAttackTime >= this.attackSpeed) {
            this.isAttacking = true;
            this.lastAttackTime = currentTime;
            
            // 添加攻击动画效果
            this.addAttackEffect();
            
            // 0.5秒后结束攻击状态
            setTimeout(() => {
                this.isAttacking = false;
            }, 500);
        }
    }
    
    takeDamage(amount) {
        this.health -= amount;
        
        // 添加受伤效果
        const originalColor = this.mesh.material.color.clone();
        this.mesh.material.color.set(0xffffff);
        
        setTimeout(() => {
            this.mesh.material.color.copy(originalColor);
        }, 100);
        
        // 播放受伤音效（如果有）
        // this.playHurtSound();
    }
    
    addAttackEffect() {
        // 创建攻击视觉效果
        const attackGeometry = new THREE.SphereGeometry(0.5, 16, 16);
        const attackMaterial = new THREE.MeshBasicMaterial({
            color: 0xff6600,
            transparent: true,
            opacity: 0.5
        });
        const attackEffect = new THREE.Mesh(attackGeometry, attackMaterial);
        
        attackEffect.position.copy(this.mesh.position);
        GAME.scene.add(attackEffect);
        
        // 动画效果
        let scale = 1;
        const animateAttack = () => {
            scale += 0.2;
            attackEffect.scale.set(scale, scale, scale);
            attackEffect.material.opacity -= 0.1;
            
            if (attackEffect.material.opacity > 0) {
                requestAnimationFrame(animateAttack);
            } else {
                GAME.scene.remove(attackEffect);
            }
        };
        
        animateAttack();
    }
    
    enterPhase2() {
        // BOSS进入第二阶段
        this.phase = 2;
        this.speed *= 1.2;
        this.damage *= 1.5;
        
        // 改变外观
        this.mesh.material.color.set(0xcc0000);
        if (this.auraMesh) {
            this.auraMesh.material.color.set(0xff6666);
            this.auraMesh.material.opacity = 0.3;
        }
        
        // 添加额外的视觉效果
        const glowGeometry = new THREE.SphereGeometry(1.5, 32, 32);
        const glowMaterial = new THREE.MeshBasicMaterial({
            color: 0xff0000,
            transparent: true,
            opacity: 0.1
        });
        this.glowMesh = new THREE.Mesh(glowGeometry, glowMaterial);
        this.glowMesh.position.copy(this.mesh.position);
        GAME.scene.add(this.glowMesh);
    }
    
    set position(pos) {
        this.mesh.position.copy(pos);
        if (this.auraMesh) this.auraMesh.position.copy(pos);
        if (this.glowMesh) this.glowMesh.position.copy(pos);
    }
}

// 生成不同类型的敌人函数
function spawnEnemy(type, position) {
    const enemy = new Enemy(type);
    if (position) {
        enemy.position = position;
    }
    return enemy;
}

// 关卡敌人生成器
function generateEnemiesForLevel(level) {
    const enemies = [];
    const baseCount = 5;
    const additionalPerLevel = 3;
    const totalCount = baseCount + (level - 1) * additionalPerLevel;
    
    // 根据关卡决定敌人类型分布
    let tankCount = 0;
    let fastCount = 0;
    let bossCount = 0;
    
    if (level >= 3) {
        tankCount = Math.floor(level / 3);
    }
    
    if (level >= 2) {
        fastCount = Math.floor(level / 2);
    }
    
    if (level % 5 === 0) {
        bossCount = 1;
    }
    
    // 生成敌人
    let regularCount = totalCount - tankCount - fastCount - bossCount;
    
    // 生成普通敌人
    for (let i = 0; i < regularCount; i++) {
        enemies.push(spawnEnemy('regular'));
    }
    
    // 生成快速敌人
    for (let i = 0; i < fastCount; i++) {
        enemies.push(spawnEnemy('fast'));
    }
    
    // 生成坦克敌人
    for (let i = 0; i < tankCount; i++) {
        enemies.push(spawnEnemy('tank'));
    }
    
    // 生成BOSS
    for (let i = 0; i < bossCount; i++) {
        enemies.push(spawnEnemy('boss'));
    }
    
    // 随机分布敌人位置
    enemies.forEach(enemy => {
        enemy.position.set(
            Math.random() * 80 - 40,
            0.5,
            Math.random() * 80 - 40
        );
    });
    
    return enemies;
}